import { useUserStore } from '@/stores'
import { refreshtoken } from '@/api/Refresh_token'
export const checkTokenValid = async () => {
  const userStore = useUserStore()
  const token = userStore.token
  
  // 1. 检查token是否存在
  if (!token) {
    console.log('Token不存在')
    return false
  }

  try {
    
    // 2. 解析token payload
  
    const payload = parseJwtPayload(token)
   
    // 3. 检查是否过期（添加5分钟缓冲期）
    const now = Date.now() / 1000
    const bufferTime = 300 // 5分钟缓冲


    if (payload.exp < now + bufferTime) {
      
      const newToken = await refreshtoken()
  
      
      if (!newToken) {
        console.error('刷新token失败')
        userStore.logout()
        return false
      }
      
      userStore.setToken(newToken)
    }
    
    return true
  } catch (error) {
    console.error('Token解析失败:', error)
    return false
  }
}

// 安全的JWT解析函数
function parseJwtPayload(token) {
  try {
    const base64Url = token.split('.')[1]
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
    const jsonPayload = decodeURIComponent(
      atob(base64)
        .split('')
        .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
        .join('')
    )
    return JSON.parse(jsonPayload)
  } catch (e) {
    throw new Error('Invalid token format')
  }
}